# -*- coding: utf-8 -*-
import shutil
import sys
import oss2
import os
from config_logger import config, log
import time

class OSSUploader:
    def __init__(self):
        # 从配置文件中获取Access Key ID和Access Key Secret
        self.access_key_id = config.get('ALIBABA_CLOUD', 'ALIBABA_CLOUD_ACCESS_KEY_ID')
        self.access_key_secret = config.get('ALIBABA_CLOUD', 'ALIBABA_CLOUD_ACCESS_KEY_SECRET')
        self.endpoint = config.get('ALIBABA_CLOUD', 'ENDPOINT')
        self.bucket_name = config.get('ALIBABA_CLOUD', 'BUCKET_NAME')
        # 使用获取的RAM用户的访问密钥配置访问凭证
        self.auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        self.bucket = oss2.Bucket(self.auth, "https://"+self.endpoint, self.bucket_name)

    def percentage(self, consumed_bytes, total_bytes):
        if total_bytes:
            rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
            # rate表示下载进度。
            print('\r{0}% '.format(rate), end='')
            sys.stdout.flush()
    def upload_file(self, local_file_path, object_key):
        # 填写Object完整路径和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
        # 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        try:
            start_time = time.time()  # 记录开始时间
            self.bucket.put_object_from_file(object_key, local_file_path, progress_callback=self.percentage)
            oss_url = self.get_object_url(object_key)
            end_time = time.time()  # 记录结束时间
            execution_time = end_time - start_time  # 计算执行时间
            log.info(f"上传成功，耗时:{execution_time}秒,url:{oss_url}")
            return oss_url
        except FileNotFoundError as e:
            log.error(e)
            return None
    def get_object_url(self, object_key):
        """
        根据Object键获取OSS的URL
        :param object_key: OSS中的Object键
        :return: OSS URL
        """
        return f'https://{self.bucket_name}.{self.endpoint}/{object_key}'

    def clear_folder(self, folder_path):
        """
        清空指定文件夹的所有内容。

        :param folder_path: 文件夹路径
        """
        # 检查文件夹是否存在
        if not os.path.exists(folder_path):
            log.info(f"文件夹 {folder_path} 不存在。")
            return

        # 遍历文件夹中的所有文件和文件夹
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            try:
                # 判断是文件还是文件夹并删除
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                    log.info(f"删除文件: {file_path}")
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
                    log.info(f"删除文件夹: {file_path}")
            except Exception as e:
                log.error(f"删除 {file_path} 时出错: {e}")
if __name__ == '__main__':
    OSSUploader().upload_file(r"D:\autoJY\dist\run_v1.3.0.exe", "video/jy/run_v1.3.0.exe")